package com.soft.collateral.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soft.collateral.entity.User;
import com.soft.collateral.entity.UserRole;
import com.soft.collateral.mapper.UserMapper;
import com.soft.collateral.mapper.UserRoleMapper;
import com.soft.collateral.service.UserService;
import com.soft.collateral.vo.PageQueryVO;
import com.soft.collateral.vo.UserLoginQueryVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @desc TODO
 * @date 2025/7/24
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper , User> implements UserService {

    private final UserMapper userMapper;
    private final UserRoleMapper userRoleMapper;

    /**
     * 用户登录
     * @param vo
     * @return
     */
    @Transactional(readOnly = true)
    @Override
    public User login(UserLoginQueryVO vo) {
        if(ObjectUtils.isEmpty(vo)){
            return null;
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasLength(vo.getUsername()) , User::getUsername , vo.getUsername())
                .eq(StringUtils.hasLength(vo.getPassword()) , User::getPassword , vo.getPassword());
        User user = baseMapper.selectOne(queryWrapper);
        return user;
    }

    /**
     * 分页查询用户
     * @param vo
     * @return
     */
    @Transactional(readOnly = true)
    @Override
    public Page<User> page(PageQueryVO vo) {

        if(ObjectUtils.isEmpty(vo)){
            return null;
        }

        //1.封装分页对象
        Page<User> page = Page.of(vo.getCurrentPage(), vo.getPageSize());
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

        // 按用户名模糊查询
        wrapper.like(StringUtils.hasLength(vo.getQueryString()), User::getUsername, vo.getQueryString())
                .or().like(StringUtils.hasLength(vo.getQueryString()), User::getNickname, vo.getQueryString());

        // 按用户ID精确查询
        if (vo.getUserId() != null) {
            wrapper.eq(User::getId, vo.getUserId());
        }

        // 按角色筛选需要联表查询，这里需要额外实现
        if (!CollectionUtils.isEmpty(vo.getRoleIds())) {
            // 需要联表查询user_role表
            wrapper.inSql(User::getId,
                    "SELECT user_id FROM user_role WHERE role_id IN (" +
                            vo.getRoleIds().stream().map(String::valueOf).collect(Collectors.joining(",")) + ")");
        }

        return userMapper.selectAllPage(page, wrapper);

    }

    /**
     * 新增用户
     * @param roleIds
     * @param user
     * @return
     */
    @Transactional
    @Override
    public boolean save(Integer[] roleIds, User user) {

        //1.先插入用户
        int i = baseMapper.insert(user);
        //2.再插入关系表中数据
        insertUserRole(roleIds , user);

        return i>0?true:false;

    }

    /**
     * 根据用户id查询角色
     * @param id
     * @return
     */
    @Transactional(readOnly = true)
    @Override
    public List<Integer> findRolesById(Integer id) {
        List<Integer> rolesId = userRoleMapper.selectList(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, id))
                .stream().map(UserRole::getRoleId).collect(Collectors.toList());
        return rolesId;
    }

    /**
     * 更新用户信息
     * @param roleIds
     * @param user
     * @return
     */
    @Transactional
    @Override
    public boolean update(Integer[] roleIds, User user) {

        //1.解除关系表中的数据
        userRoleMapper.delete(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId , user.getId()));
        //2.插入关系表中的数据
        insertUserRole(roleIds , user);
        //3.更新检用户
        int i = baseMapper.updateById(user);

        return i>0?true:false;

    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @Transactional
    @Override
    public boolean deleteById(Integer id) {

        //关系表中，解除关系
        userRoleMapper.delete(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId , id));
        //删除用户
        int i = baseMapper.deleteById(id);
        return i > 0;
    }


    /**
     * 表关系插入
     * @param roleIds
     * @param user
     */
    public void insertUserRole(Integer[] roleIds, User user) {

        Stream.of(roleIds).forEach(roleId -> {
            UserRole userRole = new UserRole();
            userRole.setRoleId(roleId);
            userRole.setUserId(user.getId());
            userRoleMapper.insert(userRole);
        });

    }


}
